package com.ruoyi.system.utlis;

import com.ruoyi.system.domain.Goods;
import com.ruoyi.system.service.IGoodsService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

public class MinioUtils {

    private static final String ENDPOINT = "http://47.111.128.72:19000";
    private static final String ACCESS_KEY = "minioadmin";
    private static final String SECRET_KEY = "minioadmin";
    private static final String BUCKET_NAME = "zhentao-project";
    private static final String CONTENT_TYPE = "image/png";

    public static String minioAdd(MultipartFile file, String name, IGoodsService iGoodsService) throws IOException {
        try {
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(ENDPOINT)
                    .credentials(ACCESS_KEY, SECRET_KEY)
                    .build();

            String uuid = UUID.randomUUID().toString();
            String objectName = uuid + file.getOriginalFilename();

            PutObjectArgs putObjectArg = PutObjectArgs.builder()
                    .contentType(CONTENT_TYPE)
                    .object(objectName)
                    .bucket(BUCKET_NAME)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .build();

            minioClient.putObject(putObjectArg);

            Goods goods = new Goods();
            goods.setImages(minioClient.getObjectUrl(putObjectArg.bucket(), putObjectArg.object()));
            goods.setGoodsName(name);
            iGoodsService.insertGoods(goods);

            return "添加成功";
        } catch (Exception e) {
            throw new IOException("文件上传失败", e);
        }
    }
}